<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
const message = useMessage()

defineOptions({ name: '发票管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const data = reactive({
  config:[],
  uploadAction: base_path+'/system/base/invoice_file',
  token: getToken(),
  card_loading:false
})

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '发票管理',
  initForm: {},
  doCreate: api.createInvoice,
  doUpdate: api.updateInvoice,
  doDelete: api.deleteInvoice,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  $table.value?.handleSearch()
  api.getConfig().then((res) => {
     data.config = res.data
  })
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '发票类型',
    key: 'type',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"medium",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.type_name })
    },
  },{
    title: '发票编号',
    key: 'no',
    width: 100,
    align: 'center',
  },{
    title: '购方名称',
    key: 'gf_name',
    width: 100,
    align: 'center',
    fixed: 'left',
  },
  {
    title: '购方税号',
    key: 'gf_no',
    width: 100,
    align: 'center',
  },
{
    title: '卖方名称',
    key: 'mf_name',
    width: 100,
    align: 'center',

  },
  {
    title: '卖方税号',
    key: 'mf_no',
    width: 100,
    align: 'center',
  },

    {
    title: '发票金额',
    key: 'price',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
{
    title: '开票日期',
    key: 'date',
    width: 100,
    align: 'center',
  },
{
    title: '关联单号',
    key: 'order_id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },



  {
    title: '操作',
    key: 'actions',
    width: 120,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          []
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定删除该用户吗?'),
          }
        ),
      ]
    },
  },
]

function isNaNValue(value) {
    return value !== value;
}

// 定义可能的字段名（按优先级排序）
const possiblePriceFields = [
  '价税合计小写',
  '价税合计(小写)',
  '价税合计',
  '价税合计（小写）'
];


const customRequestMethod = (options) => {
    data.card_loading = true
    console.log(options, 'options');
    const { file } = options.file;
    const formData = new FormData();
    formData.append('file', file);
    fetch(data.uploadAction, {
        method: 'POST',
        headers: options.headers,
        body: formData,
    })
        .then((response) => response.json())
        .then((data_ret) => {
            if (data_ret.code === 200) {
                modalForm.value.file = data_ret.data.url
                message.success('发票识别成功');

                modalForm.value.gf_name = data_ret.data.info['购买方名称']
                modalForm.value.gf_no = data_ret.data.info['购买方统一社会信用代码/纳税人识别号']
                modalForm.value.mf_name = data_ret.data.info['销售方名称']
                modalForm.value.mf_no = data_ret.data.info['销售方统一社会信用代码/纳税人识别号']
                ////
              // 遍历可能的字段，找到一个有效值
                // 遍历可能的字段，找到一个有效值
                let price = null;
                for (const field of possiblePriceFields) {
                  const value = data_ret.data.info[field];
                  if (value !== undefined) {
                    // 移除货币符号等非数字字符，并尝试转换
                    const numericValue = parseFloat(value.replace(/[^\d.-]/g, ''));
                    if (!Number.isNaN(numericValue)) {
                      price = numericValue;
                      break;
                    }
                  }
                }

                // 如果所有字段都无效，可以设置默认值（如 0）
                if (price === null || Number.isNaN(price)) {
                  price = 0; // 或者其他默认值
                }

                modalForm.value.price = price;
                ////
                modalForm.value.date = data_ret.data.info['开票日期'].replace(/年|月/g, '-').replace('日', '');
                modalForm.value.no = data_ret.data.info['发票号码']

                // options.onProgress(data);
              data.card_loading = false
            } else {
                message.error(data_ret.msg);
            }
        })
}


</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="发票列表">
        <template #action>
          <NButton  type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />上传发票
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getInvoiceList"
        >
          <template #queryBar>
            <QueryBarItem label="购方" :label-width="40">
              <NInput
                v-model:value="queryItems.gf_name"
                clearable
                type="text"
                placeholder="请输入购方名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="卖方" :label-width="40">
              <NInput
                v-model:value="queryItems.mf_name"
                clearable
                type="text"
                placeholder="请输入卖方名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="开票时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal style="width: 680px" v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave">
          <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;">

              <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm">
            <NFormItem label="发票文件" path="file" style="width:100%">
                    <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" :max="1"
                        :show-file-list=false :custom-request="customRequestMethod">
                        <NButton>上传</NButton>
                    </NUpload>
            </NFormItem>
            <NFlex>
              <NFormItem label="发票分类" path="type">
                <NSelect
                  v-model:value="modalForm.type"
                  :options="data.config.invoice_type"
                  placeholder="请选择分类"
                  label-field="name"
                  value-field="id"
                  style="width: 200px"
                />

              </NFormItem>
              <NFormItem label="发票编号" path="no">
                <NInput v-model:value="modalForm.no" style="width: 200px" clearable placeholder="发票编号" />
              </NFormItem>
            </NFlex>
                <NFlex>
                  <NFormItem label="购方名称" path="gf_name">
                    <NInput v-model:value="modalForm.gf_name"  style="width: 200px" clearable placeholder="购方名称" />
                  </NFormItem>
                  <NFormItem label="购方税号" path="gf_no">
                    <NInput v-model:value="modalForm.gf_no"  style="width: 200px" clearable placeholder="购方税号" />
                  </NFormItem>

                </NFlex>

                 <NFlex>
            <NFormItem label="卖方名称" path="mf_name">
              <NInput v-model:value="modalForm.mf_name"  style="width: 200px"  clearable placeholder="卖方名称" />
            </NFormItem>
            <NFormItem label="卖方税号" path="mf_no">
              <NInput v-model:value="modalForm.mf_no"  style="width: 200px"  clearable placeholder="卖方税号" />
            </NFormItem>
                 </NFlex>

                 <NFlex>
            <NFormItem label="发票日期" path="date">
          <n-date-picker
            v-model:formatted-value="modalForm.date"
            value-format="yyyy-MM-dd"
            type="date"
            clearable
            placeholder="请输入发票日期"
            style="width: 200px"
          />
        </NFormItem>
            <NFormItem label="发票金额" path="price">
              <NInput v-model:value="modalForm.price" clearable placeholder="发票金额" style="width: 200px"/>
            </NFormItem>
                 </NFlex>
            <NFormItem label="订单编号" path="order_id">
              <NInput v-model:value="modalForm.order_id" clearable placeholder="订单编号,如有"  style="width: 493px;"/>
            </NFormItem>

            <NFormItem label="发票备注" path="remark">
              <NInput type="textarea" v-model:value="modalForm.remark" clearable placeholder="发票备注" style="width: 493px;"/>
            </NFormItem>
            <NFormItem label="发票预览" path="remark">
              <img :src="modalForm.file" v-if="modalForm.file" style="width: 493px;height: 300px"/>
            </NFormItem>

          </NForm>

             <template #description>
              文字识别中,预计10秒
            </template>
          </n-spin>

        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
